package com.hlxt.nj.sys.action;

import com.hlxt.nj.common.LoginUtil;
import com.hlxt.nj.common.PageBean;
import com.hlxt.nj.common.PageBeanUtil;
import com.hlxt.nj.sys.model.TUser;
import org.apache.log4j.Logger;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public abstract class BaseAction {
	protected Logger log = Logger.getLogger(this.getClass());
	protected ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
	
	public HttpServletRequest getHttpRequest(){
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}
		
	public HttpSession getHttpSession(){
		return getHttpRequest().getSession();
	}

	public TUser getUser(){
		return LoginUtil.getUser();
	}
	
	public PageBean getPageBean(){
		return PageBeanUtil.getPageBean(getHttpRequest());
	}
	
	public String getParameter(String para){
		return getHttpRequest().getParameter(para);
	}

	@SuppressWarnings("unchecked")
	public Map<String, String> getParametersFromRequest(HttpServletRequest req) {
		Enumeration names = req.getParameterNames();
		Map<String, String> map = new HashMap<String, String>();
		while (names.hasMoreElements()) {
			String name = (String) names.nextElement();
			Object value = req.getParameter(name);
			if (value != null) {
				String valueStr = value.toString();
				if (value instanceof String[]) {
					valueStr = ((String[]) value)[0];
					log.debug("===== " + name + " : " + valueStr);
				}
				map.put(name, valueStr);
			}
		}
		log.debug("" + map);
		return map;
	}

	/**
	 * 获取项目的绝对路径
	 * @return
	 */
	public String getTomcatAbsoultRootPath() {
		HttpServletRequest request = getHttpRequest();
		String rootPath = request.getSession().getServletContext().getRealPath("");
		return rootPath;
	}
}
